package com.dianmi.seckill.service.impl;

import com.dianmi.seckill.common.utils.JsonUtil;
import com.dianmi.seckill.config.RocketMQConstant;
import com.dianmi.seckill.entity.SubstractStockInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author xieqiaofu
 * @date 2021/4/8
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = RocketMQConstant.SECKILL_PRODUCT_STOCK_TOPIC, consumerGroup = "seckill-consumer-stock-group")
public class PlaceOrderConsumer implements RocketMQListener<Message> {

    @Autowired
    private OrderServiceImpl orderService;

    @Override
    public void onMessage(Message msg) {
        byte[] body = msg.getBody();
        if (null == body) {
            log.warn("body is null");
        }
        String json = new String(body, StandardCharsets.UTF_8);
        log.info("data: {}", json);

        SubstractStockInfo substractStockInfo = JsonUtil.parseJson(json, SubstractStockInfo.class);
        orderService.substractStock(substractStockInfo);
    }
}
